import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
from tools.base_tools import conv_arr_to_df


# 动态检测并设置后端
try:
    matplotlib.use("TkAgg")  # 首选交互式后端
except Exception:
    matplotlib.use("Agg")  # 无法使用交互式后端时，切换到非交互后端


def visualize_data(df: pd.DataFrame, columns=None, chart_type="line", title="Visualization", xlabel="X-axis", ylabel="Y-axis"):
    """
    Visualize multiple columns of a DataFrame with the selected chart type.

    Parameters:
    - df (pd.DataFrame): The input data as a pandas DataFrame.
    - columns (list): List of column names to visualize.
    - chart_type (str): Type of chart - "line", "scatter", or "bar".
    - title (str): Title of the chart.
    - xlabel (str): Label for the X-axis.
    - ylabel (str): Label for the Y-axis.

    Returns:
    - None: Displays the plot.
    """
    df = conv_arr_to_df(df, columns)

    # plt.figure(figsize=(2, 1))
    # plt.figure(figsize=(10, 6))

    if columns is None:
        columns = df.columns

    for col in columns:
        if chart_type == "line":
            plt.plot(df.index, df[col], label=col, marker='o')
        elif chart_type == "scatter":
            plt.scatter(df.index, df[col], label=col, alpha=0.7)
        elif chart_type == "bar":
            plt.bar(df.index + columns.index(col) * 0.2, df[col], width=0.2, label=col, align='center')
        else:
            raise ValueError(f"Unsupported chart type: {chart_type}")

    plt.title(title)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.legend()
    plt.grid(True)
    plt.tight_layout()

    # 兼容显示和保存
    try:
        plt.show()
    except Exception:
        plt.savefig("visualization_output.png")
        print("图形已保存为 'visualization_output.png'")


def show_data_density_by_kde(data, title="density"):
    import seaborn as sns
    # --- 核密度分布图
    plt.clf()
    shape = data.shape
    sns.histplot(data, bins=30, kde=True, color='skyblue', edgecolor='black', alpha=0.6)
    plt.title(f'[{title}] --- data distribution - KDE --- shape: {shape}')
    plt.xlabel('value')
    plt.ylabel('density')
    plt.show()


def tabular_output(lines, decimal_places=2):
    """
    按制表符对齐输出多行数据，支持数字和小数。

    参数:
        lines (list of list of str): 每个子列表表示一行数据。
        decimal_places (int): 对小数的精度要求，默认是保留两位小数。

    返回:
        str: 格式化后的字符串，用制表符分隔。
    """
    # 确定每列的最大宽度（数字和小数支持）
    col_widths = []
    for i in range(len(lines[0])):
        max_width = max(len(str(row[i])) for row in lines)
        # 检查是否是数字并处理小数精度
        if all(isinstance(row[i], (int, float)) for row in lines):
            # 保留指定的小数位数
            max_width = max(max_width, len(f"{max(lines, key=lambda x: len(str(x[i])))[i]:.{decimal_places}f}"))
        col_widths.append(max_width)

    # 格式化每行数据
    formatted_lines = []
    for row in lines:
        formatted_row = []
        for i in range(len(row)):
            # 处理数字和小数，保留指定的小数位数
            if isinstance(row[i], (int, float)):
                formatted_row.append(f"{row[i]:.{decimal_places}f}".rjust(col_widths[i]))
            else:
                formatted_row.append(str(row[i]).ljust(col_widths[i]))
        formatted_lines.append("\t".join(formatted_row))

    return "\n".join(formatted_lines)



# 示例用法
if __name__ == "__main__":
    # 创建示例数据
    data = {
        "A": [10, 15, 20, 25],
        "B": [20, 30, 40, 50],
        "C": [30, 45, 60, 75]
    }
    df = pd.DataFrame(data)

    # 可视化为折线图
    visualize_data(df, columns=["A", "B", "C"], chart_type="line", title="Line Chart Example")

    # 可视化为散点图
    # visualize_data(df, columns=["A", "B", "C"], chart_type="scatter", title="Scatter Chart Example")
    #
    # # 可视化为柱状图
    # visualize_data(df, columns=["A", "B", "C"], chart_type="bar", title="Bar Chart Example")
